package 快递单号查询;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicHeader;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by ZhuQianli on 2018/1/27.
 */
public class APP2 {

    static Long ua = 246L;

    public static void main(String[] args) throws Exception {

        long sleep = 800;
        long start = System.currentTimeMillis();
        long count = 0L;

        for (;;) {
            try {
                f:
                for (int i = 0; i < 820; i++) {

                    List<PostData> data = getData(i);

                    for (PostData postData : data) {

                        String detail = test(postData.postId);
                        JSONObject jsonObject = JSON.parseObject(detail);
                        String status = jsonObject.getString("status");
                        if (status.equals("604")) {
                            System.out.println("被封了");
                            break f;
                        }
                        count++;
                        Thread.sleep(sleep);
                    }
                    System.out.println(System.currentTimeMillis() - start);
                    System.out.println(count);
                }
            } finally {
                System.out.println(System.currentTimeMillis() - start);
                System.out.println(count);
                System.out.println(sleep);
            }
            ua++;
            count = 0L;
            start = System.currentTimeMillis();
            sleep += 100L;
        }
    }

    private static String test(String postId) throws IOException {
        String expressType = getExpressType(postId);
        String detail = getDetail(expressType, postId);
        return detail;
    }

    private static void asd() {
        //        ArrayList<PostData> list = new ArrayList<>();
//        for (int i = 0; i < 984; i++) {
//            System.out.println(i + "/984");
//            List<PostData> data = getData(i);
//            list.addAll(data);
//        }
//
//        System.out.println(JSON.toJSONString(list));
//        FileOutputStream fileOutputStream = new FileOutputStream("C:/t1.txt");
//        fileOutputStream.write(JSON.toJSONString(list).getBytes());
//        fileOutputStream.close();

        long start = 0L;
        int count = 0;
        List<PostData> postData = null;
        try {
            StringBuilder stringBuilder = new StringBuilder();
            FileInputStream fileInputStream = new FileInputStream("C:/t1.txt");
            byte[] bs = new byte[1024];
            int len = -1;
            while ((len = fileInputStream.read(bs)) > 0) {
                stringBuilder.append(new String(bs, 0, len));
            }
            fileInputStream.close();

            postData = JSON.parseArray(stringBuilder.toString(), PostData.class);
            start = System.currentTimeMillis();
            for (PostData post : postData) {
//                String expressType = getExpressType(post.postId);
//                System.out.println(expressType + "/" + post.cpCode);
//                if (!expressType.equalsIgnoreCase(post.cpCode)) {
//                    System.out.println("error");
//                    return;
//                }
                String detail = getDetail("yunda", post.postId);
                JSONObject jsonObject = JSON.parseObject(detail);
                String message = jsonObject.getString("message");
                String status = jsonObject.getString("status");
                JSONArray data = jsonObject.getJSONArray("data");
                if (!message.equals("ok") || !status.equals("200")) {
                    System.out.println("error");
                    System.out.println(detail);
                    return;
                }
//                post.data = data;
                System.out.println(count);
                count++;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            System.out.println("时间：" + (System.currentTimeMillis() - start));
            System.out.println("次数：" + count);
//            FileOutputStream fileOutputStream = new FileOutputStream("c:/t2.txt");
//            fileOutputStream.write(JSON.toJSONString(postData).getBytes());
//            fileOutputStream.close();
        }
    }


    private static String getDetail(String type, String postId) throws IOException {
        try {
            String s = sendGet("http://www.kuaidi100.com/query?type=" + type + "&postid=" + postId + "&temp=0.20209314532872624");
            return s;
        } catch (Exception e) {
            System.out.println("retry");
            return getDetail(type, postId);
        }
    }

    private static List<PostData> getData(Integer page) throws Exception {
        List<PostData> result = new ArrayList<>(10);
        String s = sendGet("http://shangpin.tobbn.com/TradePrint/getPrintLog?userId=1758965127&start=2017-04-03&end=2018-01-29&pn=" + page);
        JSONObject jsonObject = JSON.parseObject(s);
        JSONArray res = jsonObject.getJSONArray("res");

        for (int i = 0; i < res.size(); i++) {
            JSONObject jsonObject1 = res.getJSONObject(i);
            PostData postData = new PostData();
            postData.postId = jsonObject1.getString("waybillCode");
            postData.cpCode = jsonObject1.getString("cpCode");
            result.add(postData);
        }

        return result;
    }

    static class PostData {
        public String postId;
        public String cpCode;
        public List data;
    }

    private static String getExpressType(String postId) throws IOException {
        String s = "";
        try {
            s = sendGet("http://www.kuaidi100.com/autonumber/autoComNum?resultv2=1&text=" + postId);
        } catch (Exception e) {
            System.out.println("retry");
            return getExpressType(postId);
        }
        try {
            JSONObject jsonObject = JSON.parseObject(s);
            JSONArray auto = jsonObject.getJSONArray("auto");
            String comCode = auto.getJSONObject(0).getString("comCode");

            return comCode;
        } catch (Exception e) {
            System.out.println(s);
            throw e;
        }
    }

    private static String sendGet(String url) throws Exception {
        CloseableHttpClient client = HttpClientBuilder.create().build();

        HttpGet httpGet = new HttpGet(url);

        Header[] headers = createHeaders();
        httpGet.setHeaders(headers);

        StringBuilder stringBuilder = new StringBuilder();
        try (CloseableHttpResponse execute = client.execute(httpGet)) {
            HttpEntity entity = execute.getEntity();
            InputStream content = entity.getContent();
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(content, "UTF-8"));
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                stringBuilder.append(line).append("\r\n");
            }
        } catch (Exception e) {
            throw e;
        }

        return stringBuilder.toString();


    }

    private static Header[] createHeaders() {
        List headersList = new ArrayList();
        headersList.add(new BasicHeader("accept", "application/json, text/javascript, */*; q=0.01"));
        headersList.add(new BasicHeader("accept-encoding", "gzip, deflate"));
        headersList.add(new BasicHeader("accept-language", "zh-CN,zh;q=0.9,en;q=0.8"));
        headersList.add(new BasicHeader("cookie", ""));
//        headersList.add(new BasicHeader("Host", "sp0.baidu.com"));
        headersList.add(new BasicHeader("Referer", "http://www.kuaidi100.com/?from=openv"));
        headersList.add(new BasicHeader("user-agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537."+ua+" (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537." + ua));

        return (Header[]) headersList.toArray(new Header[headersList.size()]);
    }
}
